package com.yami.shop.mystery.multishop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.StationEnum;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.BeanUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.mystery.common.vo.MysteryBoxParam;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.security.multishop.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 盲盒盒子（商户端）
 *
 * @author wxf
 * @date 2023/4/6 10:42
 */
@RestController
@RequestMapping("/activity/mysteryBox")
@Tag(name="盲盒盒子（商户端）")
public class MysteryBoxController {

    @Autowired
    private MysteryBoxService mysteryBoxService;

    @GetMapping("/page")
    @Operation(summary = "分页获取盲盒活动")
    public ServerResponseEntity<IPage<MysteryBox>> page(PageParam<MysteryBox> page, MysteryBox param) {
        YamiShopUser shopUser = SecurityUtils.getShopUser();
        param.setShopId(shopUser.getShopId());
        IPage<MysteryBox> pageBox = mysteryBoxService.getPage(page, param);
        return ServerResponseEntity.success(pageBox);
    }

    @PostMapping("/save")
    @Operation(summary = "创建盲盒盒子信息")
    public ServerResponseEntity<Void> save(@RequestBody @Valid MysteryBoxParam param) {
        MysteryBox mysteryBox = BeanUtil.map(param, MysteryBox.class);
        YamiShopUser shopUser = SecurityUtils.getShopUser();
        if (Objects.isNull(param.getProds())) {
            throw new YamiShopBindException("请选择活动商品");
        }
        mysteryBox.setShopId(shopUser.getShopId());
        mysteryBoxService.saveMysteryBox(mysteryBox);
        return ServerResponseEntity.success();
    }

    @PostMapping("/update")
    @Operation(summary = "修改盲盒盒子信息")
    public ServerResponseEntity<Void> update(@RequestBody @Valid MysteryBoxParam param) {
        MysteryBox mysteryBox = BeanUtil.map(param, MysteryBox.class);
        mysteryBoxService.updateMysteryBox(mysteryBox);
        return ServerResponseEntity.success();
    }

    @PutMapping("/invalid/{id}")
    @Operation(summary =  "通过id使盲盒盒子失效")
    @Parameter(name = "id", description = "盲盒盒子id", required = true)
    public ServerResponseEntity<Void> invalidById(@PathVariable Long id, @RequestBody MysteryBox pram) {
        MysteryBox box = mysteryBoxService.getById(id);
        if (!SecurityUtils.getShopUser().getShopId().equals(box.getShopId())) {
            throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED);
        }
        if (Objects.equals(box.getStatus(), StationEnum.OFFLINE.getValue())) {
            throw new YamiShopBindException("盲盒盒子已违规下架，无法关闭");
        }
        // 判断盲盒当前是否参加活动，如果是不能修改
        if (box.getProdType() != 0 && StationEnum.INVALID.getValue() == pram.getStatus()) {
            throw new YamiShopBindException("盲盒盒子正在参加活动，不能被下架");
        }
        box.setStatus(pram.getStatus());
        mysteryBoxService.invalidById(box);
        return ServerResponseEntity.success();
    }

    @PutMapping("/invalid")
    @Operation(summary =  "通过id使盲盒盒子失效")
    public ServerResponseEntity<Boolean> invalidById(@RequestBody MysteryBox pram) {

        Long[] ids = pram.getIds();
        StringBuilder stringBuilder = new StringBuilder();
        for (Long id : ids) {
            MysteryBox box = mysteryBoxService.getById(id);
            try {
                if (!SecurityUtils.getShopUser().getShopId().equals(box.getShopId())) {
                    throw new YamiShopBindException(ResponseEnum.UNAUTHORIZED);
                }
                if (Objects.equals(box.getStatus(), StationEnum.OFFLINE.getValue())) {
                    throw new YamiShopBindException("盲盒盒子已违规下架，无法关闭");
                }
                // 判断盲盒当前是否参加活动，如果是不能修改
                if (box.getProdType() != 0 && StationEnum.INVALID.getValue() == pram.getStatus()) {
                    throw new YamiShopBindException("盲盒盒子正在参加活动，不能被下架");
                }
                box.setStatus(pram.getStatus());
                mysteryBoxService.invalidById(box);

            } catch (Exception e) {
                stringBuilder.append("【").append(box.getBoxName()).append("】  ");
            }
        }
        if (stringBuilder.length() > 0) {
            throw new YamiShopBindException("部分盲盒失效异常，请刷新页面后手动检查：" + stringBuilder.toString());
        }
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除盲盒盒子")
    @Parameter(name = "id", description = "盲盒盒子id", required = true)
    public ServerResponseEntity<Void> deleteMysteryBox(@PathVariable Long id) {

        mysteryBoxService.deleteMysteryBox(id);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "根据盲盒盒子id列表批量删除盲盒盒子", description = "根据盲盒盒子id列表批量删除盲盒盒子")
    public ServerResponseEntity<Boolean> batchDeleteMysteryBox(@RequestBody Long[] ids) {

        StringBuilder stringBuilder = new StringBuilder();
        for (Long id : ids) {
            try {
                mysteryBoxService.deleteMysteryBox(id);
            } catch (Exception e) {
                MysteryBox box = mysteryBoxService.getById(id);
                stringBuilder.append("【").append(box.getBoxName()).append("】  ");
            }
        }
        if (stringBuilder.length() > 0) {
            throw new YamiShopBindException("部分盲盒删除异常，请刷新页面后手动检查：" + stringBuilder.toString());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/info/{id}")
    @Operation(summary = "获取盲盒活动详细信息")
    public ServerResponseEntity<MysteryBox> info(@PathVariable("id") Long id) {
        MysteryBox coupon = mysteryBoxService.detail(id);
        return ServerResponseEntity.success(coupon);
    }

    @PutMapping("/batchMysteryBoxStatus")
    @Operation(summary = "批量更新商品状态")
    public ServerResponseEntity<Void> batchMysteryBoxStatus(@RequestBody Long[] ids, Integer status) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Long id : ids) {
            try {
                mysteryBoxService.mysteryBoxStatus(id, status);
            } catch (Exception e) {
                MysteryBox box = mysteryBoxService.getById(id);
                stringBuilder.append("【" + box.getBoxName() + "】:" + e.getMessage() + "\n");
            }
        }
        if (stringBuilder.length() > 0) {
            throw new YamiShopBindException("部分商品状态修改异常，请刷新页面后手动检查：" + stringBuilder.toString());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/getListData")
    @Operation(summary = "获取盲盒列表")
    public ServerResponseEntity<List<MysteryBox>> getListData(){
        YamiShopUser shopUser = SecurityUtils.getShopUser();
        List<MysteryBox> listBox = mysteryBoxService.getListData(shopUser.getShopId());
        return ServerResponseEntity.success(listBox);
    }

    @GetMapping("/getBoxList")
    @Operation(summary = "获取正常状态下的盲盒列表(空投页面使用)")
    public ServerResponseEntity<List<MysteryBox>> getMysteryBoxList(){
        // 状态（0:失效、1:正常、2:违规下架、3:等待审核、4:审核失败）
        YamiShopUser shopUser = SecurityUtils.getShopUser();
        List<MysteryBox> listBox = mysteryBoxService.getListByShopIdAndStatus(shopUser.getShopId(),null);
        return ServerResponseEntity.success(listBox);
    }

    @PostMapping("/createQrcode")
    @Operation(summary = "生成二维码和链接")
    public ServerResponseEntity<Void> createQrcode(@RequestBody @Valid MysteryBox param) {
        if (Objects.isNull(param.getId()) || Objects.isNull(param.getShopId())) {
           throw new YamiShopBindException("请求参数不完整！");
        }
        MysteryBox box = mysteryBoxService.getById(param.getId());
        if (StringUtils.isNotBlank(box.getQrcodeAddr())) {
            throw new YamiShopBindException("二维码和链接已生成成功，请勿重复生成！");
        }
        mysteryBoxService.createQrcode(param.getId(), param.getShopId());
        return ServerResponseEntity.success();
    }

    @GetMapping( "/getLinkData")
    @ResponseBody
    @Operation(summary =  "查看Link信息", description = "查看Link信息")
    public ServerResponseEntity<MysteryBox> getLinkData(Long boxId){
        MysteryBox box = mysteryBoxService.getById(boxId);
        return ServerResponseEntity.success(box);
    }

}
